package loquendo.asr.demo;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.EOFException;
import java.io.RandomAccessFile;

import android.util.Log;
import com.loquendo.asr.*;

public class FileAudioSource implements ASRAudioSource
{
	private static final String LOGTAG = "FileAudioSource";

	boolean m_bIsStopped;
	String m_szFilePath;
    RandomAccessFile m_oFile;
	byte[] m_abyBuffer;
    int m_nLength;	
	int m_nWhere;
	int m_nHowMany;
	
	public FileAudioSource()
	{
		m_bIsStopped = true;
		m_szFilePath = null;
		m_nLength = 0;
	    m_abyBuffer = null;
	    m_nWhere = 0;
	    m_nHowMany = 1024;
	}
	
	public void SetFile(String szFilePath) throws ASRParameterException
	{
		m_szFilePath = szFilePath;
		RandomAccessFile oFile = null;
		try { oFile = new RandomAccessFile(m_szFilePath, "r"); }
		catch (FileNotFoundException oException) { Log.d(LOGTAG, "File '" + m_szFilePath + "' not found."); }
		try 
		{ 
			m_nLength = (int)oFile.length();
			m_abyBuffer = new byte[m_nLength];
			oFile.readFully(m_abyBuffer);
			oFile.close();
		}
		catch (IOException oException) { Log.d(LOGTAG, "Unable to load file '" + m_szFilePath + "'."); }	
	}
	
	public void Open() 
	{
		Log.d(LOGTAG, "AudioOpen START");
		Log.d(LOGTAG, "AudioOpen END");
	}
	public void Close() 
	{
		Log.d(LOGTAG, "AudioClose START");
		Log.d(LOGTAG, "AudioClose END");
	}
	public void Start() 
	{ 
		Log.d(LOGTAG, "AudioStart START");
		m_bIsStopped = false; 
	    m_nWhere = 0;
		Log.d(LOGTAG, "AudioStart END");
	}
	public void Stop()
	{ 
		Log.d(LOGTAG, "AudioStop START");
		m_bIsStopped = true; 
		Log.d(LOGTAG, "AudioStop END");
	}
	public boolean IsStopped() 
	{ 
		Log.d(LOGTAG, "AudioIsStopped START");
		Log.d(LOGTAG, "AudioIsStopped END");
		return m_bIsStopped; 
	}
	public byte[] GetSampleBuffer()
	{
		Log.d(LOGTAG, "AudioGetSampleBuffer START");
		byte[] abyBuffer = null;
	    if (m_abyBuffer != null)
	    {
		    if (m_nHowMany < 0)
		    {
		        abyBuffer = m_abyBuffer;
		    }
		    else 
		    {
		        int nHowMany = m_nLength - m_nWhere;
		        if (nHowMany > 0)
		{ 
		            if (nHowMany > m_nHowMany) nHowMany = m_nHowMany;
		            abyBuffer = new byte[nHowMany];
		            for (int nIdx = 0; nIdx < nHowMany; nIdx++) abyBuffer[nIdx] = m_abyBuffer[m_nWhere++];
		        }

		}
	 	}
		Log.d(LOGTAG, "AudioGetSampleBuffer END");
		return abyBuffer;
	}
}
